package other.xsy.passlys.account;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.data.model.Department;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import other.xsy.passlys.util.CustomAdminUtil;
import other.xsy.passlys.util.HCXObjectService;
import other.xsy.passlys.util.HcUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 编辑客户前: 需要进行重复判断
 * @Author 黎炎松
 * 2024-06-28 11:46
 */
public class AccountUpdateBeforeTrigger implements Trigger {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private XoqlService xoqlService = XoqlService.instance();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "编辑客户进行是否重复判断 ==> ";

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.debug(LOGGER_MSG + " 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Account> accountList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Account account = (Account) xObject;
            accountList.add(account);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        dataResultList.set(0, accountIsExist(accountList.get(0)));
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        Account account = new Account();
        account.setId(3471438748244569L);
        account = hcxObjectService.get(account);
        //account.setKaBody__c(3);
        new AccountUpdateBeforeTrigger().accountIsExist(account);
    }


    /**
     * 客户重复判断
     * @param account
     */
    public DataResult accountIsExist(Account account){
        try {
            logger.info(LOGGER_MSG + " 处理开始:" + account);
            String accountName = account.getAccountName(); // 客户名称 accountName


            // 编辑只需要判断是否有重复的客户名称即可、排除自己
            //String sql = "select id from account where id != " + account.getId() + " and accountName = '" + accountName + "'";
            String sql = "select id from account where accountName = '" + accountName + "'";
            QueryResult<JSONObject> query = CustomAdminUtil.sendAdminXoqlQuery(sql);
            if (!query.getSuccess()) {
                logger.error(LOGGER_MSG + " 查询异常");
                return new DataResult(false, "查询异常", account);
            }

            logger.debug(LOGGER_MSG + " query:" + query.getRecords());
            if (query.getTotalCount() > 0) {

                // 获取旧的客户名称，如果名称没有进行编辑则放行
                List<JSONObject> accountList = query.getRecords();
                JSONObject filterAccount = accountList.stream().filter(v -> v.getLong("id").equals(account.getId())).findAny().orElse(null);
                if (filterAccount != null) {
                    logger.info(LOGGER_MSG + "客户名称没有进行编辑");
                    return new DataResult(true,"" , account);
                }

                logger.error(LOGGER_MSG + " 客户名称已存在");
                return new DataResult(false, "客户名称已存在", account);
            }

            // 判断NA客户上限
            CheckAddAccountCount checkAddAccountCount = new CheckAddAccountCount();
            ApprovalEventResponse approvalEventResponse = checkAddAccountCount.checkAccountCounts(account);
            if (!approvalEventResponse.getSuccess()) {
                // 已达上限，不允许编辑
                String msg = approvalEventResponse.getMsg();
                logger.error(LOGGER_MSG + msg);
                return new DataResult(false, msg, account);
            }

            // 允许编辑
            logger.info(LOGGER_MSG + " 客户不存在，允许编辑客户");
            return new DataResult(true,"" , account);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " 处理异常:" + e.getMessage());
            return new DataResult(false, "处理异常:" + e.getMessage(), account);
        }
    }


}
